package com.example.security.exception;

import com.example.security.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.example.security.vo.SsoTokenResponse;
import com.example.security.vo.SsoUserInfo;

/**
 * 全局异常处理器
 * 统一处理系统中的异常情况
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    private boolean isOAuthRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            String uri = attributes.getRequest().getRequestURI();
            return uri.startsWith("/api/oauth/");
        }
        return false;
    }

    /**
     * 处理权限不足异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public Result<Void> handleAccessDeniedException(AccessDeniedException e) {
        log.error("权限不足: {}", e.getMessage());
        return Result.fail(403, "权限不足");
    }

    /**
     * 处理认证异常
     */
    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result<?> handleAuthenticationException(AuthenticationException e) {
        log.error("认证失败: ", e);
        return Result.fail(401, "认证失败");
    }

    /**
     * 处理Token相关异常 - 针对API返回Result的情况
     */
    @ExceptionHandler(InvalidTokenException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Object handleInvalidTokenException(InvalidTokenException e) {
        log.error("Token无效: {}", e.getMessage());
        
        if (isOAuthRequest()) {
            return new SsoUserInfo();
        }
        
        return Result.fail(401, e.getMessage());
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleBusinessException(BusinessException e) {
        log.error("业务异常: {}", e.getMessage());
        return Result.fail(e.getMessage());
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleValidException(MethodArgumentNotValidException e) {
        FieldError fieldError = e.getBindingResult().getFieldError();
        String message = fieldError != null ? fieldError.getDefaultMessage() : "参数错误";
        log.error("参数校验失败: {}", message);
        return Result.fail(message);
    }

    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public Result<Void> handleBindException(BindException e) {
        FieldError fieldError = e.getBindingResult().getFieldError();
        String message = fieldError != null ? fieldError.getDefaultMessage() : "参数错误";
        log.error("参数绑定失败: {}", message);
        return Result.fail(message);
    }

    /**
     * 处理BadCredentials异常 - 针对SSO认证的情况
     */
    @ExceptionHandler(BadCredentialsException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Object handleBadCredentials(BadCredentialsException e) {
        log.error("认证失败: {}", e.getMessage());
        
        if (isOAuthRequest()) {
            SsoTokenResponse response = new SsoTokenResponse();
            response.setAccessToken(null);
            response.setTokenType("Bearer");
            response.setExpiresIn(0L);
            return response;
        }
        
        return Result.fail(401, "认证失败");
    }

    /**
     * 处理其他未知异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> handleException(Exception e) {
        log.error("系统异常", e);
        return Result.fail(500, "系统异常：" + e.getMessage());
    }
} 